package com.zhanlv.composer

import android.util.Log
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.lang.Exception
import java.net.ServerSocket
import java.net.Socket


object SocketServer {
    private const val TAG = "SocketServer"

    private var serverSocket: ServerSocket? = null

    private var socket: Socket? = null

    private var result = true

    fun start(port: Int){
        Thread(Runnable {
            try {
                Log.i(TAG, "=========== start")
                serverSocket = ServerSocket(port)

                Log.i(TAG, "serverSocket: $serverSocket")

                while (result){
                    Log.i(TAG, "while true")

                    try {
                        socket = serverSocket?.accept()
                    }catch (e: Exception){
                        Log.i(TAG, "accpt error")
                    }

                    Log.i(TAG, "socket: $socket")

                    socket?.let {
                        Log.i(TAG, "WorkThread: start")
                        ServerWorkThread(it).start()
                    }
                }
            }catch (e: IOException){
                Log.e(TAG, "start error: " + e.message)
            }

        }).start()
    }
}

